package com.webex.ta.hydra.gui.search;

import com.webex.ta.hydra.core.Command;
import com.webex.ta.hydra.core.TestPlan;
import com.webex.ta.hydra.Constants;

import java.util.Enumeration;

/**
 * Author: Vegaz
 * Date: 2010-10-28
 * Time: 16:08:03
 */
public class SearchEngine {
    public static FindResult searchFrom(String search, TestPlan tp, Command start, int col, int caret) {
        Enumeration<Command> enumer = tp.preorderEnumeration();
        Command next = null;
        while (enumer.hasMoreElements()) {
            next = enumer.nextElement();
            if (start == next)
                break;
        }

        if (next == null)
            return null;

        FindResult r = startSearchInCommand(search, next, col, caret);
        if (r!= null)
            return r;

        while (enumer.hasMoreElements()) {
            next = enumer.nextElement();
            FindResult r1 = startSearchInCommand(search, next, 0, 0);
            if (r1 != null)
                return r1;
        }
        return null;
    }

    private static FindResult startSearchInCommand(String search, Command cmd, int col, int caret) {
        int columnCount = cmd.getParameterSize() + 1;
        FindResult result = new FindResult();
        result.setCommand(cmd);
        int r = -1;
        if (col < columnCount) {
            String text = getColumnText(cmd, col);
            r = startSearchInString(search, text, caret);
            if (r >= 0) {
                result.setColumn(col);
                result.setCaret(r);
                return result;
            }
        }
        col ++;
        while (col < columnCount) {
            String text = getColumnText(cmd, col);
            r = startSearchInString(search, text, 0);
            if (r >= 0) {
                result.setColumn(col);
                result.setCaret(r);
                return result;
            }
            col ++;
        }
        return null;
    }

    private static String getColumnText(Command cmd, int col) {
        switch (col) {
            case 0:
                return cmd.getKeyword();
            default:
                return cmd.getParameter(col -1);
        }
    }

    // return the new caret;
    private static int startSearchInString(String search, String text, int caret) {
        if (text == null || text.length() == 0 || text.length() <= caret) {
            return -1;
        }

        String str = text.substring(caret);
        int start = str.indexOf(search);
        if (start < 0)
            return -1;

        return start + caret + search.length();
    }
}
